#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

const int MAX_BUFFER_SIZE = 10;

/// @brief 
/// 生产者消费者模型

class ProducerConsumer {
private:
    std::queue<int> buffer;
    std::mutex mtx;
    std::condition_variable cond_producer, cond_consumer;
    bool stop_requested = false;

public:
    void producer(int id) {
        while (true) {
            std::unique_lock<std::mutex> lock(mtx);
            
            // 等待缓冲队列非满
            cond_producer.wait(lock, [this]() {
                return buffer.size() < MAX_BUFFER_SIZE || stop_requested;
            });

            if (stop_requested) break;

            // 生产数据
            int item = rand() % 1000;
            buffer.push(item);
            std::cout << "Producer " << id << " produced: " << item 
                      << " (Buffer size: " << buffer.size() << ")\n";

            // 通知消费者
            cond_consumer.notify_one();
            lock.unlock();
            
            // 模拟生产耗时
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    }

    void consumer(int id) {
        while (true) {
            std::unique_lock<std::mutex> lock(mtx);

            // 等待缓冲队列非空
            cond_consumer.wait(lock, [this]() {
                return !buffer.empty() || stop_requested;
            });

            if (stop_requested && buffer.empty()) break;

            // 消费数据
            int item = buffer.front();
            buffer.pop();
            std::cout << "Consumer " << id << " consumed: " << item 
                      << " (Buffer size: " << buffer.size() << ")\n";

            // 通知生产者
            cond_producer.notify_one();
            lock.unlock();
            
            // 模拟消费耗时
            std::this_thread::sleep_for(std::chrono::milliseconds(150));
        }
    }

    void stop() {
        std::unique_lock<std::mutex> lock(mtx);
        stop_requested = true;
        cond_producer.notify_all();
        cond_consumer.notify_all();
    }
};

int main() {
    ProducerConsumer pc;

    // 创建2个生产者线程和3个消费者线程
    std::vector<std::thread> producers;
    std::vector<std::thread> consumers;

    for (int i = 0; i < 2; ++i) {
        producers.emplace_back(&ProducerConsumer::producer, &pc, i+1);
    }

    for (int i = 0; i < 3; ++i) {
        consumers.emplace_back(&ProducerConsumer::consumer, &pc, i+1);
    }
    //  while(true){

    //  };
    
    // // 运行5秒后停止
    // std::this_thread::sleep_for(std::chrono::seconds(5));
    // pc.stop();

    // // 等待所有线程结束
    // for (auto& p : producers) p.join();
    // for (auto& c : consumers) c.join();

    return 0;
}